#-------------------------------------------------------------------------------
# Name:        xml_to_notes_converter.py
# Purpose:     Classes to convert XML file from LibreOffice plugin
#              to a SlideSpeech sequence
#
# Authors:     John Graves <john.graves@slidespeech.com>
#
# Copyright:   (c) Slidespeech Ltd 2012
# Licence:     MIT license
#-------------------------------------------------------------------------------

import os, sys, shutil, urllib

from xml.sax import make_parser, handler

from converter import Converter
from zipfile import ZipFile

class NoteHandler(handler.ContentHandler):
    """A ContentHandler to extract the text from <paragraph> elements"""
    def __init__(self):
        self.noteText = ""
        self.noteList = []
        self.inNotesElement = 0

    def startElement(self, name, attrs):
        if "paragraph"==name:
            self.inNotesElement = 1

    def characters(self, ch):
        if self.inNotesElement:
            self.noteText = self.noteText + ' ' + ch

    def endElement(self, name, ):
        if "paragraph"==name:
            self.inNotesElement = 0
            self.noteList.append(urllib.unquote(self.noteText))
            self.noteText = ""


class XmlToNotesConverter(Converter):
    def __init__(self, xmlPath=None, xmlFile='slide-notes.xml', previous=None):
        Converter.__init__(self, previous)
        if xmlPath is None:
            if hasattr(self,'_xmlPath'):
                pass
            else:
                self._xmlPath = os.path.join(self.tempDir(),'CONTENTS')
        else:
            self._xmlPath = xmlPath
        self._xmlFile = xmlFile

    def _convertImpl(self):
        """Extracts text from <paragraph> element in the XML file
        Returns a list with the notes from each element as a separate item."""
        parser = make_parser()
        handler = NoteHandler()
        parser.setContentHandler(handler)
        try:
            f = open(os.path.join(self._xmlPath,self._xmlFile),"r")
            parser.parse(f)
            f.close()

    ##        if __debug__: # won't execute if Python is run with the -O flag
    ##            print("Notes found in doc:")
    ##            for note in handler.noteList:
    ##                print(note)

        except Exception as ex:
            # FIXME: record exception details
            raise ex

        # add the image file locations to the script
        try:
            newSeq = {'S':[]}
            for note in handler.noteList:
                newSeq['S'].append({'q':note})
            seq = self.script()
            del seq['S']
            seq['S'] = newSeq['S']

        except KeyError as e:
            ex = ConverterError("Field missing in slide script", e)
            raise ex

if __name__ == "__main__":
    # a simple test/demo with default XML file
    c = XmlToNotesConverter( os.path.join(os.getcwd(),'CONTENTS') )
    c.convert()
    print(c.script())
